<template>
  <view class="list-page">
    <!-- 字典类型信息 -->
    <view class="dict-type-info">
      <view class="info-item">
        <text class="info-label">字典名称：</text>
        <text class="info-value">{{ dictName }}</text>
      </view>
      <view class="info-item">
        <text class="info-label">字典类型：</text>
        <text class="info-value">{{ dictType }}</text>
      </view>
    </view>

    <!-- 搜索栏 -->
    <view class="list-search-bar">
      <view class="list-search-input">
        <uni-icons type="search" size="16" color="#999"></uni-icons>
        <input v-model="queryParams.dictLabel" class="list-input" placeholder="搜索字典标签" @input="handleSearchInput"
               @confirm="handleSearch"/>
        <uni-icons v-if="queryParams.dictLabel" type="clear" size="16" color="#999" @click="handleClear"></uni-icons>
      </view>
      <view class="list-filter-btn" @click="toggleFilter">
        <uni-icons type="filter" size="14" color="#666"></uni-icons>
        <text>筛选</text>
      </view>
    </view>

    <!-- 筛选抽屉 -->
    <uni-popup ref="filterPopup" type="right" :mask-click="false">
      <view class="list-filter-drawer">
        <view class="list-filter-header">
          <text class="list-filter-title">高级筛选</text>
          <uni-icons type="close" size="20" @click="closeFilter"></uni-icons>
        </view>
        <view class="list-filter-content">
          <view class="list-filter-item">
            <text class="list-filter-label">字典键值</text>
            <uni-easyinput v-model="queryParams.dictValue" placeholder="请输入字典键值" :clearable="true"/>
          </view>
          <view class="list-filter-item">
            <text class="list-filter-label">状态</text>
            <BottomSelect v-model="queryParams.status" :options="statusOptions" value-field="value" label-field="text"
                          placeholder="请选择状态" title="选择状态"/>
          </view>
        </view>
        <view class="list-filter-footer">
          <view class="btn btn-reset" @click="handleFilterReset">重置</view>
          <view class="btn btn-confirm" @click="handleFilterConfirm">确定</view>
        </view>
      </view>
    </uni-popup>

    <!-- 操作按钮栏 -->
    <view class="list-action-bar">
      <view class="btn btn-primary" @click="handleAdd" v-if="checkPermission(['system:dict:add'])">
        <uni-icons type="plus" size="14" color="#007aff"/>
        <text>新增</text>
      </view>
      <view class="btn btn-default" @click="handleRefresh">
        <uni-icons type="reload" size="14" color="#666"/>
        <text>刷新</text>
      </view>
    </view>

    <!-- 列表 -->
    <view class="list-content">
      <view v-for="(data, index) in dataList" :key="index" class="list-item" @click="handleView(data)">
        <view class="list-avatar">
          <uni-icons type="gear" size="24" :color="data.status === '0' ? '#1890ff' : '#d9d9d9'"></uni-icons>
        </view>
        <view class="list-info">
          <view class="list-header">
            <view class="label-display">
              <!-- 根据listClass和cssClass显示不同样式的标签 -->
              <uni-tag
                  v-if="data.listClass && data.listClass !== 'default'"
                  :text="data.dictLabel"
                  :type="getTagType(data.listClass)"
                  :class="data.cssClass"
                  size="normal">
              </uni-tag>
              <text v-else class="list-title plain-label" :class="data.cssClass">{{ data.dictLabel }}</text>
            </view>
            <text class="list-subtitle">键值: {{ data.dictValue }}</text>
            <view class="status-badge" :class="data.status === '0' ? 'status-normal' : 'status-disabled'">
              {{ data.status === '0' ? '正常' : '停用' }}
            </view>
          </view>
          <view class="list-details">
            <view class="detail-item">
              <uni-icons type="up-down" size="14" color="#999"/>
              <text class="detail-text">排序：{{ data.dictSort }}</text>
            </view>
            <view class="detail-item" v-if="data.remark">
              <uni-icons type="compose" size="14" color="#999"/>
              <text class="detail-text">{{ data.remark }}</text>
            </view>
          </view>
        </view>
        <view class="list-actions">
          <view class="action-btn action-primary" @click.stop="handleUpdate(data)"
                v-if="checkPermission(['system:dict:edit'])">
            <uni-icons type="compose" size="14" color="#007aff"/>
            <text class="action-text">编辑</text>
          </view>
          <view class="action-btn action-danger" @click.stop="handleDelete(data)"
                v-if="checkPermission(['system:dict:remove'])">
            <uni-icons type="trash" size="14" color="#ff3b30"/>
            <text class="action-text">删除</text>
          </view>
        </view>
      </view>
    </view>

    <view v-if="dataList.length > 0" class="list-load-more">
      <uni-load-more :status="loadStatus" :content-text="loadText" @clickLoadMore="handleLoadMore"/>
    </view>

    <view v-if="!loading && dataList.length === 0" class="list-empty">
      <uni-icons type="gear" size="48" color="#ddd"/>
      <text class="list-empty-text">暂无字典数据</text>
      <button class="btn btn-primary" @click="handleAdd" v-if="checkPermission(['system:dict:add'])">添加数据</button>
    </view>
  </view>
</template>

<script setup>
import {computed, getCurrentInstance, reactive, ref} from 'vue'
import {onLoad} from '@dcloudio/uni-app'
import {delData, listData} from '@/api/system/dict/data'

import {usePermission} from '@/utils/permission'
import {BottomSelect} from '@/components/select'

const {proxy} = getCurrentInstance()


const checkPermission = usePermission()

// 页面参数
const dictType = ref('')
const dictName = ref('')

// 数据定义
const dataList = ref([])
const total = ref(0)
const loading = ref(false)
const loadStatus = ref('more')

const loadText = reactive({
  contentdown: '上拉显示更多',
  contentrefresh: '正在加载...',
  contentnomore: '没有更多数据了'
})

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  dictType: '',
  dictLabel: '',
  dictValue: '',
  status: ''
})

// 计算属性
const navTitle = computed(() => {
  return dictName.value ? `${dictName.value} - 数据管理` : '字典数据管理'
})

// 选项数据
const statusOptions = [
  {value: '', text: '全部状态'},
  {value: '0', text: '正常'},
  {value: '1', text: '停用'}
]

const filterPopup = ref(null)
let searchTimer = null

// ==================== 修复：使用 onLoad 生命周期钩子 ====================
onLoad((options) => {
  if (options.dictType) {
    dictType.value = options.dictType
    dictName.value = options.dictName || ''
    queryParams.dictType = options.dictType
    
    // 设置页面标题
    uni.setNavigationBarTitle({
      title: dictName.value ? `${dictName.value} - 数据管理` : '字典数据管理'
    })
    
    getList()
  } else {
    proxy.$modal.showToast('缺少字典类型参数')
  }
})

// 获取字典数据列表
async function getList() {
  if (loading.value) return

  loading.value = true
  loadStatus.value = 'loading'

  try {
    const response = await listData(queryParams)
    if (response.code === 200) {
      const newData = response.rows || []

      if (queryParams.pageNum === 1) {
        dataList.value = newData
      } else {
        dataList.value.push(...newData)
      }

      total.value = response.total || 0

      // 判断是否还有更多数据
      if (dataList.value.length >= total.value) {
        loadStatus.value = 'noMore'
      } else {
        loadStatus.value = 'more'
      }
    }
  } catch (error) {
    console.error('获取字典数据列表失败:', error)
    proxy.$modal.showToast('获取字典数据列表失败')
    loadStatus.value = 'more'
  } finally {
    loading.value = false
  }
}

// 筛选相关函数
function toggleFilter() {
  filterPopup.value.open()
}

function closeFilter() {
  filterPopup.value.close()
}

function handleFilterConfirm() {
  closeFilter();
  handleQuery()
}

function handleFilterReset() {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    dictType: queryParams.dictType,
    dictLabel: '',
    dictValue: '',
    status: ''
  })
}

function handleSearchInput() {
  if (searchTimer) clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    handleQuery()
  }, 300)
}

function handleSearch() {
  handleQuery()
}

function handleClear() {
  queryParams.dictLabel = '';
  handleQuery()
}

// 刷新
function handleRefresh() {
  queryParams.pageNum = 1
  dataList.value = []
  getList()
  proxy.$modal.showToast('刷新成功')
}

// 搜索
function handleQuery() {
  queryParams.pageNum = 1
  dataList.value = []
  getList()
}

// 加载更多
function handleLoadMore() {
  if (loadStatus.value === 'more' && !loading.value) {
    queryParams.pageNum++
    getList()
  }
}

// 新增字典数据
function handleAdd() {
  uni.navigateTo({
    url: `/pages_system/dict/data-edit?type=add&dictType=${dictType.value}&dictName=${dictName.value}`
  })
}

// 查看字典数据详情
function handleView(data) {
  uni.navigateTo({
    url: `/pages_system/dict/data-edit?mode=view&dictCode=${data.dictCode}&dictType=${dictType.value}&dictName=${dictName.value}`
  })
}

// 修改字典数据
function handleUpdate(data) {
  uni.navigateTo({
    url: `/pages_system/dict/data-edit?mode=edit&dictCode=${data.dictCode}&dictType=${dictType.value}&dictName=${dictName.value}`
  })
}

// 删除字典数据
async function handleDelete(data) {
  const result = await proxy.$modal.confirm(`是否确认删除字典数据"${data.dictLabel}"？`)
  if (result) {
    try {
      const response = await delData(data.dictCode)
      if (response.code === 200) {
        proxy.$modal.showToast('删除成功')
        queryParams.pageNum = 1
        dataList.value = []
        getList()
      } else {
        proxy.$modal.showToast(response.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      proxy.$modal.showToast('删除失败')
    }
  }
}

// 返回上一页
function handleBack() {
  uni.navigateBack()
}

// 获取字典标签
function getDictLabel(options, value) {
  const option = options.find(item => item.value === value)
  return option ? option.text : '未知'
}

// 获取标签类型
function getTagType(listClass) {
  const typeMap = {
    'primary': 'primary',
    'success': 'success',
    'info': 'primary',
    'warning': 'warning',
    'danger': 'error',
    'default': 'default'
  }
  return typeMap[listClass] || 'default'
}
</script>

<style lang="scss" scoped>
@import '@/styles/list-page.scss';

.dict-type-info {
  background-color: #fff;
  padding: 15px;
  margin-bottom: 10px;
  border-bottom: 1px solid #eee;

  .info-item {
    display: flex;
    margin-bottom: 8px;

    &:last-child {
      margin-bottom: 0;
    }

    .info-label {
      font-size: 14px;
      color: #666;
      margin-right: 8px;
      min-width: 80px;
    }

    .info-value {
      font-size: 14px;
      color: #333;
      font-weight: 500;
    }
  }
}

.label-display {
  .plain-label {
    font-size: 16px;
    font-weight: bold;
    color: #333;
  }
}

/* 自定义CSS类样式 */
:global(.text-red) {
  color: #ff4d4f !important;
}

:global(.text-green) {
  color: #52c41a !important;
}

:global(.text-blue) {
  color: #1890ff !important;
}

:global(.text-orange) {
  color: #fa8c16 !important;
}

:global(.text-purple) {
  color: #722ed1 !important;
}
</style>